<template>
  <div id="schedule">
    <div class="title">Schedule</div>
    <div class="content">
      <div class="top-content">
        <Row>
          <i-col span="7">
            <Row class="date-select">
              <i-col class="item" span="6" @click.native="changeDay('left')"><i class="iconfont">&#xe617;</i></i-col>
              <i-col class="item" span="6">Today</i-col>
              <i-col class="item" span="6">
                <Date-picker
                  :open="dateOpen"
                  type="date"
                  v-model="selectDay"
                  @on-change="dateChange">
                  <i @click="dateOpen = true" class="iconfont">&#xe66a;</i>
                </Date-picker>
              </i-col>
              <i-col class="item" span="6" @click.native="changeDay('right')"><i class="iconfont">&#xe618;</i></i-col>
            </Row>
          </i-col>
          <i-col class="text-center" span="10">
            <div class="current-show">{{currentShow}}</div>
          </i-col>
          <i-col class="clearfix" span="7">
            <Row class="type-select l">
              <i-col class="item" span="8" @click.native="type='day'" :class="{active:type=='day'}">Day</i-col>
              <i-col class="item" span="8" @click.native="type='week'" :class="{active:type=='week'}">Week</i-col>
              <i-col class="item" span="8" @click.native="type='month'" :class="{active:type=='month'}">Month</i-col>
            </Row>
            <div class="publish-button r">
              <Button type="primary">Published</Button>
            </div>
          </i-col>
        </Row>
      </div>

      <div class=" table-content" >
        <i-table  v-if="dayColumns" v-show="type=='day'" class="table-panel"  border :columns="dayColumns" :data="dayData"></i-table>
        <i-table  v-if="weekColumns" v-show="type=='week'" class="table-panel"  border :columns="weekColumns" :data="weekData"></i-table>
        <div v-show="type=='month'">
          <table class="calendar-content">
            <tr class="header-row">
              <th class="calendar-cell" v-for="(item,key) in weeks">
                {{item}}
              </th>
            </tr>
            <tr class="content-row" v-if="monthCalendarRows" v-for="(cells,key) in monthCalendarRows" :key="key">
              <td @click="addSchedule(cell.year+'-'+cell.month+'-'+cell.day)"  class="calendar-cell" :class="[cell.className]"   v-for="(cell,key) in cells">
                <div class="date-title"> {{cell.text}}</div>
                <div  class="month-schedule-content" v-if="monthData&&monthData[cell.year+'-'+cell.month+'-'+cell.day]">
                    <div @click.stop="editSchedule(item,$event)" class="month-schedule-item" @mouseenter="scheduleHover($event,item.color)" @mouseleave="scheduleHoverLeave($event)"  :style="{backgroundColor:item.color}" v-for="(item,key) in monthData[cell.year+'-'+cell.month+'-'+cell.day]">
                      {{item.startTimeView + ' - ' + item.endTimeView  +item.note}}
                    </div>
                </div>
               </td>
            </tr>
          </table>
        </div>
      </div>
    </div>

    <!--=============================-->
    <div v-show="showEditSchedule" class="edit-schedule">
      <div  v-if="scheduleItemData" class="title">{{formatEditDate(scheduleEditModel.scheDate)}}</div>
      <div  v-if="scheduleItemData" class="form">
        <Form class="my-form schedule-edit-form"  v-model="scheduleEditModel" label-position="left" :label-width="100">
          <Form-item label="START DATE">
            <Row>
              <i-col span="16">
                <Date-picker v-model="scheduleEditModel.scheDate" type="date"   style="width: 146px"></Date-picker>
              </i-col>
              <i-col span="8">
                <el-checkbox :true-label="1" :fasle-label="0" v-model="scheduleEditModel.isAllDay" style="width: 100px"> ALL DAY</el-checkbox>
              </i-col>
            </Row>
          </Form-item>
          <Form-item label="START TIME">
            <Select  v-model="scheduleEditModel.startTime" style="width: 82px">
              <Option v-for="(item,key) in timeList" :key="item" :value="item">{{item}}</Option>
            </Select>
          </Form-item>
          <Form-item label="END TIME">
            <Select  v-model="scheduleEditModel.endTime"  style="width: 82px">
              <Option v-for="(item,key) in timeList" :key="item" :value="item">{{item}}</Option>
            </Select>
            <span style="margin-left: 12px">0h</span>
          </Form-item>
          <Row>
            <i-col span="17">
              <Form-item label="TITLE">
                <Input  v-model="scheduleEditModel.scheTitle"  style="width: 146px"></Input>
              </Form-item>
            </i-col>
            <i-col span="7">
           <Form-item label="COLOR" :label-width="70">
                <d-color-picker v-model="scheduleEditModel.color" ></d-color-picker>
              </Form-item>
            </i-col>
          </Row>
          <Form-item label="TIME ZONE">
            <Select  v-model="scheduleEditModel.scheTimeZone"  style="width: 146px">
              <Option v-for="(item,key) in scheduleItemData.timeZone" :key="item.value" :value="item.value">{{item.name}}</Option>
            </Select>
          </Form-item>
          <Form-item label="EMPLOYEES">
            <Select v-model="scheduleEditModel.employees" filterable multiple>

            </Select>
          </Form-item>
          <Form-item v-model="scheduleEditModel.location"  label="LOCATION">
           <Input>
          </Form-item>
          <Form-item label="NOTE">
            <Input v-model="scheduleEditModel.notes">
          </Form-item>
          <div style="height: 60px">
            <Checkbox> REPEAT </Checkbox>
          </div>
          <div class="btn-group">
            <Button class="default-btn" @click="showEditSchedule = false">Cancel</Button>
            <Button class="default-btn">Save Draft</Button>
            <Button class="default-btn active" @click="saveSchedule">Save</Button>
          </div>
        </Form>
      </div>
    </div>
  </div>
</template>
<script>
  import dColorPicker from 'src/components/common/colorPicker.vue'
  export default {
    name: 'Schedule',
    components:{
      dColorPicker

    },
    created(){
      this.init();
    },
    data () {
      return {
        type:'day',
        today:'',
        startDate:null,
        endDate:null,
        beginEndType:null,
        weeks:['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        monthCalendarRows:[],
        dateOpen:false,
        selectDay:'',
        dayColumns:null,
        weekColumns:null,
        monthColumns:null,
        dayCellWidth: 40,
        currentShow:'---',
        dayData:[],
        weekData:[],
        monthData:{},
        timeList:[
          '00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:30', '06:30',
        ],
        showEditSchedule:false,
        scheduleItemData:null,
        scheduleEditModel:{
          "scheduleId": null,
          "scheDate":null,
          "isAllDay": 0,
          "startTime": null,
          "endTime": null,
          "scheTimeZone":null,
          "scheTitle":null,
          "color": null,
          "employeeId": 0,
          "location": null,
          "notes": null,
          "isPublished": null,	//是否已经发布，0：未发布，1：已发布
          "scheRepeatId": null,
         /* "isRepeat": 1,	//是否循环排班，0：否，1：是
          "repeatType": 1,
          "repeatFrequency": 1,
          "monthRepeatOn": "",
          "weekRepeatOn": "",
          "repeatEndDate": "",
          "repeatEndType": 1,*/
        }
      }
    },
    watch:{
      type(newValue){
        if(this.type == 'day'){
          this.startDate = this.selectDay;
          this.endDate = null;
        }else if(this.type == 'week'){
          this.startDate = moment(this.selectDay).startOf('week').format('YYYY-MM-DD');
          this.endDate = moment(this.selectDay).endOf('week').format('YYYY-MM-DD');
        }else if(this.type == 'month'){
          this.startDate = moment(this.selectDay).startOf('month').format('YYYY-MM-DD');
          this.endDate = moment(this.selectDay).endOf('month').format('YYYY-MM-DD');
        }
        this.changeBeginEndType()
      },
      selectDay(value){
        if(this.type == 'day'){
          this.startDate = value;
          this.endDate = null;
        }else if(this.type == 'week'){
          this.startDate = moment(value).startOf('week').format('YYYY-MM-DD');
          this.endDate = moment(value).endOf('week').format('YYYY-MM-DD');
        }else if(this.type == 'month'){
          this.startDate = moment(value).startOf('month').format('YYYY-MM-DD');
          this.endDate = moment(value).endOf('month').format('YYYY-MM-DD');
        }
        this.changeBeginEndType()
      },
      daySchedule(value){
        this.dayData = value&&value.pageInfo&&value.pageInfo.records? value.pageInfo.records : [];
      },
      weekSchedule(value){
        this.weekData = value&&value.pageInfo&&value.pageInfo.records? value.pageInfo.records : [];
      },
      monthSchedule(value){
        this.monthData = value;
      },
      beginEndType(){
        this.initTable();
      }
    },
    computed:{
      daySchedule(){
        return this.$store.getters.daySchedule;
      },
      weekSchedule(){
        return this.$store.getters.weekSchedule;
      },
      monthSchedule(){
        return this.$store.getters.monthSchedule;
      }
    },
    methods:{
      init(){
        this.today = moment().format('YYYY-MM-DD');
        this.selectDay = this.today;
      },
      formatEditDate(date){
        return moment(date).format('dddd,MMM D,YYYY');
      },
      changeBeginEndType(){
      	this.beginEndType = this.type + this.startDate + this.endDate;
      },
      handleChange(){

      },
      initTable(type){
        if(this.type == 'day'){
        	this.dayColumns = this.initDayColumns();
          this.$store.dispatch('getDaySchedule',{startDate:this.startDate,endDate:this.endDate});

        }else if(this.type == 'week'){

          this.$store.dispatch('getWeekSchedule',{startDate:this.startDate,endDate:this.endDate});
          this.weekColumns = this.initWeekColumns();

        }else if(this.type == 'month'){
          this.$store.dispatch('getMonthSchedule',{startDate:this.startDate,endDate:this.endDate});
          this.monthCalendarRows = this.initMonth();
        }else{
        	console.log('no Type');
        	return;
        }

      },
      initDayColumns(type){
      	var t = this;
        var columns = [];
        t.selectDay = moment(t.selectDay).format('YYYY-MM-DD');
        t.currentShow = moment(t.selectDay).format('MMM DD / YYYY');
        //添加第一列employee name
        columns.push({
          key:"name",
          title:'group',
          width:'150px',
          className:'employee-name-column',
          ellipsis:true,
          render:function (row,column,index) {
            return `<d-avatar name="${row.name}" img-url="${row.imgUrl}" :width="30"></d-avatar>`
          }
        });
        //时间列
        for(var i = 0 ;i < 24;i++) {
        	var num = i<12?(i==0?12:i):(i>12?i-12:i),unit = 'am';
        	if(i>=12){
        		unit = 'pm';
          }
          columns.push({
            key:i,
            width:t.dayCellWidth +'px',
            title:num + unit,
          });
        }
        //添加空列
        columns.push({
          key:'',
          title:' ',
        });
        /*render 时间轴*/
        columns[1].className = 'employee-schedule-column';
        columns[1].render = function(row, column, index){
          if(!row.schedules){
            return
          }
          var schedules = row.schedules[Object.keys(row.schedules)[0]];
          var items =[];
          for(var i = 0;i<schedules.length;i++){
          	var item = schedules[i];
            var startTime = new Date(item.startTimeView).getTime(),
                endTime = new Date(item.endTimeView).getTime(),
                selectTime = new Date(t.selectDay+' 00:00:00').getTime(),
                left = (startTime - selectTime)/1000/3600 * t.dayCellWidth,
                right = (endTime - selectTime)/1000/3600 * t.dayCellWidth,
                bgColor = schedules[i].color,
                textMargin = left<0?-left + 'px':0,
                showText = moment(item.startTimeView).format('hh:mm') + ' - ' + moment(item.endTimeView).format('hh:mm');
            items.push(
            	`<div class="item" @mouseenter="scheduleHover($event,'${bgColor}')" @mouseleave="scheduleHoverLeave($event)"  style="left: ${left}px;width:${right-left}px;background-color: ${bgColor};box-shadow-color:${bgColor}">
                <span style="margin-left: ${textMargin}">${showText}</span>
              </div>`
            );
          }
          return items.join("");
        }
        return columns;
      },
      initWeekColumns(){
        var t = this;
        var columns = [];
        //添加第一列employee name
        columns.push({
          key:"name",
          title:'group',
          width:'150px',
          className:'employee-name-column',
          ellipsis:true,
          render:function (row,column,index) {
            return `<d-avatar name="${row.name}" img-url="${row.imgUrl}" :width="30"></d-avatar>`
          }
        });
        var weekFirstDay = moment(t.selectDay).startOf('week'),
            weekEndDay = moment(t.selectDay).endOf('week');
        t.currentShow = weekFirstDay.format('MMM DD - ') + weekEndDay.format('MMM DD / YYYY');
        for(var i=0;i<7;i++){
          columns.push({
            title:moment(t.selectDay).startOf('week').add(i,'days').format('ddd M/D'),
            key:moment(t.selectDay).startOf('week').add(i,'days').format('YYYY-MM-DD'),
            className:'week-schedule',
            render:function (row, column, index) {
              var schedules = row.schedules,
                  key = column.key;
              var str = '';
              if(schedules[key]){
              	for(var j = 0;j< schedules[key].length;j++){
                  str += `<div class="week-schedule-item"  @mouseenter="scheduleHover($event,'${schedules[key][j].color}')"  @mouseleave="scheduleHoverLeave($event)"  style="background-color:${schedules[key][j].color}">
                            ${moment(schedules[key][j].startTimeView).format('HH:MM')} - ${moment(schedules[key][j].endTimeView).format('HH:MM')}  ${schedules[key][j].scheTitle}
                          </div>`;
                }
              }
              return str;
            }
          })
        }
      	return columns;
      },
      initMonth(){
      	var t = this;
      	var year = new Date(this.selectDay).getFullYear();
      	var month = new Date(this.selectDay).getMonth() + 1;
        t.currentShow = moment(t.selectDay).startOf('month').format('MMM DD - ') + moment(t.selectDay).endOf('month').format('MMM DD / YYYY');
        const ROW = 6;
        const COLUMN = 7;
        var day = new Date(year,month - 1).getDay();
        var currentCells = [],
          currentLength = new Date(year,month,0).getDate();

        for(var i = 1 ;i <= currentLength;i++ ){
          let classNames = [];
          year == new Date().getFullYear() && month == new Date().getMonth() + 1 && new Date().getDate() == i &&  classNames.push('cur-date');
          currentCells.push({text:i,year:year,month:month<10?'0'+month:month,day:i<10?'0'+i:i,className:classNames.join(" ")});
        }

        //之前cells
        var preYear = month - 1 == 0 ? year - 1 : year;
        var prevMonth = month - 1 == 0 ? 12 : month - 1;
        var preLastDay = new Date(preYear,prevMonth,0).getDate();

        var preLength = day;
        var preCells = [];
        for(var i = 0 ;i < preLength;i++ ){
          let classNames = ['pre'];
          preCells.push({text:preLastDay - i,year:preYear,month:prevMonth<10?'0'+prevMonth:prevMonth,day:i<10?'0'+i:i,className:classNames.join(" ")});
        }
        preCells.reverse();

        //之后cells
        var nextYear = month + 1 == 13 ? year + 1 : year;
        var nextMonth = month + 1 == 13 ? 1 : month + 1;
        var nextFirstDay = 1;
        var nextCells = [],nextLength = ROW*COLUMN - preLength - currentLength;
        for(var i = 0 ;i < nextLength;i++ ){
          let classNames = ['next'];
          nextCells.push({text:nextFirstDay + i,year:nextYear,month:nextMonth<10?'0'+nextMonth:nextMonth,day:i<10?'0'+i:i,className:classNames.join(" ")});
        }

        var cells = preCells.concat(currentCells,nextCells),
          rows = [];
        for(var i=0;i<ROW;i++){
          rows[i] = cells.slice(COLUMN*i,COLUMN*(i+1));
        }
        return rows;
      },
      dateChange(value){
      	this.selectDay = value;
        this.dateOpen = false
      },
      /*排版hover加阴影*/
      scheduleHover(e,color){
      	var opacityColor = `rgba(${this.colorToRgbArr(color).join(",")},0.5)`;
        e.target.style.boxShadow = `0 2px 4px 0 ${opacityColor}`;
      },
      scheduleHoverLeave(e){
        e.target.style.boxShadow = '';
      },
      changeDay(leftOrRight){
        if(this.type == 'day'){
          this.selectDay = moment(this.selectDay)[leftOrRight=='right'?'add':'subtract'](1,'days');
        }else if(this.type == 'week'){
          this.selectDay = moment(this.selectDay)[leftOrRight=='right'?'add':'subtract'](1,'week');
        }else if(this.type == 'month'){
          this.selectDay = moment(this.selectDay)[leftOrRight=='right'?'add':'subtract'](1,'month');
        }
      },
      /**
       * 点击scheduleItem，编辑schedule
       * @param scheduleItem
       * @param e
       */
      editSchedule(scheduleItem,e){
        this.scheduleEditModel.scheduleId = scheduleItem.scheduleId;
        this.$store.dispatch('getScheduleDetail',{
          scheduleId:scheduleItem.scheduleId,
          scheRepeatId:scheduleItem.scheRepeatId,
          typeId:1
        }).then(
          (data)=>{
            this.scheduleItemData = data.data;
            for(var i in this.scheduleEditModel){
              if(this.scheduleItemData.schedule[i]){
                this.scheduleEditModel[i] = this.scheduleItemData.schedule[i];
              }
            }
            this.showEditSchedule = true;
          }
        )
      },
      addSchedule(date){
        this.$store.dispatch('getScheduleDetail',{
          scheduleId:null,
          scheRepeatId:null,
          typeId:1
        }).then(
          (data)=>{
            this.scheduleItemData = data.data;
            for(var i in this.scheduleEditModel){
              if(this.scheduleItemData.schedule[i]){
                this.scheduleEditModel[i] = this.scheduleItemData.schedule[i];
              }
            }
            this.showEditSchedule = true;
          }
        )
      },
      saveSchedule(){
        var paramData = JSON.parse(JSON.stringify(this.scheduleEditModel));
        if(paramData.scheDate){
          paramData.scheDate = moment(paramData.scheDate).format('YYYY-MM-DD');
        }
        this.$store.dispatch('saveSchedule',paramData).then(
          ()=>{
            this.$Message.success('edit success!');
            this.showEditSchedule = false;
            this.initTable();
          }
        ) ;
      },
      colorToRgbArr(color){
        var color = color.toLowerCase();
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        if(color && reg.test(color)){
          if(color.length === 4){
            var colorNew = "#";
            for(var i=1; i<4; i+=1){
              colorNew += color.slice(i,i+1).concat(color.slice(i,i+1));
            }
            color = colorNew;
          }
          //处理六位的颜色值
          var colorChange = [];
          for(var i=1; i<7; i+=2){
            colorChange.push(parseInt("0x"+color.slice(i,i+2)));
          }
          return  colorChange;
        }else{
          return null;
        }
      }
    }
  }
</script>


<style  rel="stylesheet/scss" type="text/css" lang="scss"  >
  @import "src/assets/css/variable";
  #schedule{
    >.title{

    }
    >.content{
      .top-content{
        height: 34px;
        line-height: 34px;
        margin-bottom: 20px;
        .date-select{
          width: 200px;
          border: 1px solid $baseBorderColor;
          border-radius: 2px;
          /*font-family: PingFangTC-Regular;*/
          font-size: 12px;
          color: #325570;
          .item{
            height: 100%;
            text-align: center;
            border-right: 1px solid $baseBorderColor;
            cursor: pointer;
            .ivu-date-picker{
              display: inline-block;
            }
            &:last-child{
              border-right: none;
            }
            &:hover{
              .iconfont{
                opacity: .7;
              }

            }
          }
        }
        .current-show{
         /* font-family: PingFangTC-Regular;*/
          font-size: 18px;
          color: #325570;
        }
        .type-select{
          width: 210px;
          border: 1px solid $baseBorderColor;
          border-radius: 2px;
          /*font-family: PingFangTC-Regular;*/
          font-size: 12px;
          color: #325570;
          .item{
            height: 100%;
            text-align: center;
            border-right: 1px solid $baseBorderColor;
            cursor: pointer;
            &:last-child{
              border-right: none;
            }
            &:hover{
              opacity: .7;
            }
            &.active{
              background-color: $baseColor;
              color: #fff;
            }
          }
        }
        .publish-button{
          button{
            width: 100px;
            height: 100%;
            background: #009AFF;
            border-radius: 2px;
            &:hover{
              opacity: .7;
            }
          }
        }
      }
      .table-content{
        .table-panel{
          .ivu-table-header  th{
            font-size: 12px;
          }
          .ivu-table-cell{
            width: 100%;
            padding: 0;
            text-align: center;
          }
          .employee-name-column{
            position: relative;
            z-index: 11;
            .ivu-table-cell{
              padding: 0 8px ;
              text-align: left;
            }
            .avatar-name{
              display: inline-block;
              width: 30px;
              height: 30px;
              line-height: 30px;
              text-align: center;
              margin-right: 5px;
              vertical-align: middle;
              background-color: #61c62b;
              color:#fff;
              border-radius: 50%;
            }
            .avatar-img{
              display: inline-block;
              width: 30px;
              height: 30px;
              line-height: 30px;
              margin-right: 5px;
              vertical-align: middle;
            }
          }
          .employee-schedule-column{
            position: relative;
            .item{
              position: absolute;
              left: 0px;
              top:8px;
              width: 0;
              height: 34px;
              line-height: 34px;
              padding: 0 20px;
              background: #78D000;
           /*   box-shadow: 0 2px 4px 0 rgba(119,208,0,0.50);*/
              border-radius: 39px;
             /* font-family: PingFangTC-Regular;*/
              font-size: 12px;
              color: #FFFFFF;
              text-align: left;
              transition: all .3s;
              z-index:10;
            }
          }
          .week-schedule{
            vertical-align: top;
            padding: 4px;
            .week-schedule-item{
              width: 100%;
              height: 32px;
              line-height: 13px;
              padding: 3px;
              margin-bottom: 4px;
              font-size: 12px;
              color: #fff;
              text-align: left;
            }
          }
        }
        .calendar-content{
          width: 100%;
          border-top: 1px solid $baseBorderColor ;
          border-left: 1px solid $baseBorderColor ;
          .content-row{
            height: 84px;
            .calendar-cell{
              position: relative;
              width: 166px;
              padding: 26px 4px 16px 4px;
              text-align: center;
              vertical-align: top;
              border-right: 1px solid $baseBorderColor ;
              border-bottom: 1px solid $baseBorderColor ;
              &.pre,&.next{
                color:#999;
              }
              &.cur-date{
                .date-title{
                  background-color: $baseColor;
                  color: #fff;
                }
              }
              .date-title{
                position: absolute;
                top: 4px;
                left: 8px;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                font-size: 12px;
                color: #325570;
              }
              .month-schedule-content{
                .ivu-poptip{
                  width: 100%;
                  .ivu-poptip-rel{
                    width: 100%;
                  }
                }
                .month-schedule-item{
                  font-size: 12px;
                  color: #FFFFFF;
                  height: 20px;
                  line-height: 20px;
                  background-color: $baseColor;
                  border-radius: 72px;
                  margin-bottom: 4px;
                  width: 156px;
                  padding: 0 12px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  cursor: pointer;
                }
              }
            }
          }
          .header-row{
            height: 52px;
            background: #F2F9FF;
            font-size: 14px;
            color: #96ACB9;
            .calendar-cell{
              text-align: center;
              border: 0;
              &:last-child{
                border-right: 1px $baseBorderColor solid;
              }
            }
          }
        }
      }
    }
    /*=================================*/
    .edit-schedule{
      position: fixed;
      width: 550px;
      height: 660px;
      top: 25%;
      left: 35%;
      padding: 40px 68px;
      background: #FFFFFF;
      border: 1px solid $baseBorderColor;
      box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
      border-radius: 4px;
      z-index: 101;
      >.title{
        line-height: 28px;
        margin-bottom: 30px;
        font-size: 20px;
        color: #325570;
      }
      .schedule-edit-form{
        .ivu-form-item{
          margin-bottom: 18px;
          .ivu-form-item-label{
            color: #96ACB9;
          }
        }
        .btn-group{
          text-align: center;
          margin: 10px auto;
          button{
            margin: 0 12px;
          }
        }
      }
    }
  }
</style>
